package actions.accounts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.xwork.ObjectUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;

import data.Account;

import actions.base.BaseAction;

public class Login extends BaseAction {

	@Override
	public String execute() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		Object value = session.getAttribute("userName");
		String test = ObjectUtils.defaultIfNull(value, "").toString();
		if (!test.equals(""))
			return redirect("/staffs/Listing.action");
		else {
			String username = getUsername();
			String password = getPassword();
			Account account;
			if (StringUtils.isNotEmpty(username)
					&& StringUtils.isNotEmpty(password)) {
				account = services.getAccount(username, password);
				if (account != null) {
					int role = account.getAccountRole().getAccountRoleId();
					boolean status = account.getStaff().getStaffStatus();
					if (role == 1 && status) {
						request.getSession().setAttribute("username",
								username);
						return redirect("/complaints/Listing.action");
					}
				}
			}
		}
		if("logout".equals(request.getParameter("action"))){
			request.getSession().invalidate();
		}
		return SUCCESS;
	}

	String username;
	String password;
	boolean remember;

	/**
	 * @return the userName
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username
	 *            the userName to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the remember
	 */
	public boolean isRemember() {
		return remember;
	}

	/**
	 * @param remember
	 *            the remember to set
	 */
	public void setRemember(boolean remember) {
		this.remember = remember;
	}

}
